import time

from loguru import logger
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtCore import QThread, pyqtSignal, QStringListModel, QTimer
from ui.Ui_main_window import Ui_MainWindow
from common.qt_worker import Worker
import sys


class MainWindow(QMainWindow):

    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.__init_ui()
        self.worker: Worker = None

        q_timer = QTimer()
        q_timer.timeout.connect(self.update_worker_list)
        q_timer.start(200)

    def __task(self, worker: Worker, *args, **kwargs):
        thread_id = QThread.currentThread()
        logger.debug("ThreadId:{}", thread_id)

        ms_sleep = kwargs.get("sleep", 1000)

        counter = 0
        while worker.is_running:
            worker.emit_msg((thread_id, counter))
            counter += 1
            time.sleep(ms_sleep * 0.001)
        return "good!"

    def msg_handler(self, msg):
        thread_id, counter = msg
        logger.info("msg:{} {} ", thread_id, counter)

    def __start_task(self):
        interval_ms = self.ui.sb_interval.value()
        self.worker = Worker(self.__task, kwargs={"sleep": interval_ms})
        self.worker.signal_connect(
            finished_handler=lambda: logger.info("finished"),
            result_handler=lambda result: logger.debug("rst:{}", result),
            error_handler=lambda e: logger.error("error:{}", e),
            msg_handler=self.msg_handler
        )
        self.worker.start()

    def update_worker_list(self):
        pass

    def __stop_task(self):
        logger.warning("stop worker")
        self.worker.stop()

    def __init_ui(self):
        self.ui.btn_start.clicked.connect(self.__start_task)
        self.ui.btn_stop.clicked.connect(self.__stop_task)


if __name__ == '__main__':
    app = QApplication(sys.argv)

    window = MainWindow()
    window.show()

    sys.exit(app.exec_())
